package frame.system;

import frame.base.Ajax;
import frame.system.service.PermissionService;
import frame.system.service.RoleService;
import frame.system.service.UserService;
import frame.system.to.User;
import frame.util.shiro.LoginUser;
import frame.util.shiro.UserMD5;
import frame.util.shiro.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class SystemWeb {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;


    @GetMapping({"/","/login"})
    public String login(Model model) {
        final Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/web/main";
        } else {
            model.addAttribute("msg", "");
            return "system/login";
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public Ajax login(LoginUser loginUser) {
        final Subject subject = SecurityUtils.getSubject();
        loginUser.setSessionId(subject.getSession().getId().toString());
        try {
            User user = userService.doLogin(loginUser);
            UsernamePasswordToken token = new UsernamePasswordToken(loginUser.getUsername(), loginUser.getPassword());
            subject.login(token);
            //TODO 后期改成配置
            user.setBaseboardUrl("https://www.baidu.com/");
            UserRealm.setSystemUserLogin(user);
            return Ajax.success(System.currentTimeMillis(),"");
        } catch (Exception e) {
            return Ajax.faild(e.getMessage());
        }
    }

    /**
     * Web端心跳
     */
    @RequestMapping("/web/heartbeat")
    @ResponseBody
    public Ajax heartbeat() {
        return Ajax.success(System.currentTimeMillis(),"");
    }
    /**
     * 页面容器
     * 填入当然
     * @return
     */
    @RequestMapping("/web/main")
    public String main() {
        return "system/main";
    }

    /**
     * 用户菜单
     * @return
     */
    @RequestMapping("/web/main/menu")
    @ResponseBody
    public Ajax menu() {
        try {
            Integer id = UserRealm.getSystemUserLoginId();
            return Ajax.success(permissionService.allPermissionMenu(id), "用户菜单成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Ajax.faild("用户菜单查询失败：" + e.getMessage());
        }
    }

    /**
     * 登陆用户修改自己的密码
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @PostMapping("/web/main/updatepassword")
    @ResponseBody
    public Ajax updatePassword(@RequestParam("oldPwd") String oldPwd, @RequestParam("newPwd") String newPwd) {
        try {
            Integer id = UserRealm.getSystemUserLoginId();
            User user = userService.selectByPrimaryKey(id);
            String md5 = UserMD5.doMd5(oldPwd, user.getSalt());
            if (!md5.equals(user.getPassword())) throw new Exception("旧密码错误！");
            user.setPassword(newPwd);
            int re = userService.updatePassword(user);
            return Ajax.success(re,"密码修改成功！");
        } catch (Exception e) {
            return Ajax.faild("密码修改失败：" + e.getMessage());
        }
    }
    @RequestMapping("/web/main/loginUser")
    @ResponseBody
    public Ajax loginUser() {
        User user = UserRealm.getSystemUserLogin();
        return Ajax.success(user, "当前登陆用户角色消息查询成功");
    }

    @RequestMapping("/403")
    @ResponseBody
    public String error403() {
        return "权限不足，请联系管理员！";
    }

    @Autowired
    SessionDAO sessionDAO;
    @Autowired
    MemorySessionDAO memorySessionDAO;
    @Autowired
    DefaultWebSessionManager sessionManager;

    @RequestMapping("/online")
    @ResponseBody
    public Ajax online() {
        try {
            System.out.println(sessionDAO == memorySessionDAO);
            System.out.println(sessionManager.getSessionDAO() == sessionDAO);
            Collection<Session> sessions = sessionDAO.getActiveSessions();
            final Subject subject = SecurityUtils.getSubject();
            final Session session1 = subject.getSession();
            System.out.println(session1.getId());
            sessions.forEach(session -> {
                System.out.println(session.getId() +  " " +session.getTimeout());

            });
            int re = 0;
            return Ajax.success(sessions, "成功！");
        } catch (Exception e) {
            return Ajax.faild("失败：" + e.getMessage());
        }
    }

}
